<!--  时间项目管理图 -->
<template>
  <el-card v-for="(item, index) in timeProjectList" :key="index">
    <template #header>
      <div class="title">
        时间管理:{{ item[0].name }}
        <el-tooltip effect="dark" content="点击试试下载" placement="bottom">
          <i-ep-download class="download" @click="downloadEchart" />
        </el-tooltip>
      </div>
    </template>

    <div
      :id="`${id}${index}`"
      :class="className"
      :style="{ height, width }"
    ></div>
  </el-card>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { getStatisticsPage } from "@/api/time/project";
import {
  TimeProjectStatisticsPageVO,
  TimeProjectPageQuery,
} from "@/api/time/types";
import { nextTick } from "vue";

const props = defineProps({
  id: {
    type: String,
    default: "lineChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});

const options = {
  grid: {
    left: "2%",
    right: "2%",
    bottom: "10%",
    containLabel: true,
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
      crossStyle: {
        color: "#999",
      },
    },
  },
  legend: {
    x: "center",
    y: "bottom",
    data: ["项目名称", "选项", "占比", "完成率"],
    textStyle: {
      color: "#999",
    },
  },
  xAxis: [
    {
      type: "category",
      data: [],
      axisPointer: {
        type: "shadow",
      },
    },
  ],
  yAxis: [
    {
      type: "value",
      min: 0,
      max: 200,
      // interval: 0,
      axisLabel: {
        formatter: "{value}%",
      },
    },
  ],
  series: [
    {
      name: "收入",
      type: "line",
      smooth: true, // 添加这一行来使线条平滑
      data: [7000, 6100, 7200, 7300, 7400],
      itemStyle: {
        color: "#188df0",
      },
      lineStyle: {
        width: 3,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "#83bff6" },
          { offset: 1, color: "#188df0" },
        ]),
      },
    },
    {
      name: "毛利润",
      type: "line",
      smooth: true, // 添加这一行来使线条平滑
      data: [8000, 7200, 8400, 8600, 8800],
      itemStyle: {
        color: "#179e61",
      },
      lineStyle: {
        width: 3,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "#25d73c" },
          { offset: 1, color: "#179e61" },
        ]),
      },
    },
    {
      name: "收入增长率",
      type: "line",
      smooth: true, // 添加这一行来使线条平滑
      yAxisIndex: 1,
      data: [60, 66, 70, 75, 80],
      itemStyle: {
        color: "#67C23A",
      },
    },
    {
      name: "利润增长率",
      type: "line",
      smooth: true, // 添加这一行来使线条平滑
      yAxisIndex: 1,
      data: [70, 44, 80, 85, 90],
      itemStyle: {
        color: "#409EFF",
      },
    },
  ],
};

const optionsArr = ref<any[]>([]);

const downloadEchart = () => {
  charts.value.forEach((chart) => {
    downloadEchartImage(chart);
  });
};

function downloadEchartImage(chart: any) {
  console.log("downloadEchartImage" + chart);
  // 获取画布图表地址信息
  const img = new Image();
  img.src = chart.value.getDataURL({
    type: "png",
    pixelRatio: 1,
    backgroundColor: "#fff",
  });
  // 当图片加载完成后，生成 URL 并下载
  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    if (ctx) {
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const link = document.createElement("a");
      link.download = `图.png`;
      link.href = canvas.toDataURL("image/png", 0.9);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
  };
}

const charts = ref<any[]>([]);

const timeProjectList = ref<TimeProjectStatisticsPageVO[][]>();

const queryParams = reactive<TimeProjectPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

/** 查询 */
function handleQuery() {
  // loading.value = true;

  getStatisticsPage(queryParams).then(({ data }) => {
    timeProjectList.value = data.list;
    if (data.list.length === 0) {
      return;
    }
    // set options
    optionsArr.value = [];
    timeProjectList.value?.forEach((item) => {
      let optionCopy = JSON.parse(JSON.stringify(options));
      optionCopy.xAxis[0].data = item[0].days;
      optionCopy.yAxis[0].max = Math.max(
        ...item.map((i) => Math.max(...i.percentage))
      );
      optionCopy.legend.data = item.map((i) => i.name);
      optionCopy.series = item.map((i) => {
        return {
          name: i.name,
          type: "line",
          smooth: true, // 添加这一行来使线条平滑
          data: i.percentage,
          itemStyle: {
            color: i.color,
          },
          // lineStyle: {
          //   width: 3,
          //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //     {
          //       offset: 0,
          //       color:
          //         i.linearGradientColor[0] ||
          //         "#" + Math.floor(Math.random() * 16777215).toString(16),
          //     }, // default to black if i.color is undefined
          //     {
          //       offset: 1,
          //       color:
          //         i.linearGradientColor[1] ||
          //         "#" + Math.floor(Math.random() * 16777215).toString(16),
          //     }, // default to black if i.color is undefined
          //   ]),
          // },
        };
      });
      optionsArr.value.push(optionCopy);
    });

    // 图表初始化
    optionsArr.value.forEach((options, index) => {
      let chart = ref<any>("");
      // 图表初始化
      nextTick(() => {
        chart.value = markRaw(
          echarts.init(
            document.getElementById(`${props.id}${index}`) as HTMLDivElement
          )
        );

        chart.value.setOption(options);

        // 大小自适应
        window.addEventListener("resize", () => {
          chart.value.resize();
        });
        charts.value.push(chart);
      });
    });
  });
}

onMounted(() => {
  // 查询
  handleQuery();
});

onActivated(() => {
  charts.value.forEach((chart) => {
    if (chart.value) {
      chart.value.resize();
    }
  });
});
</script>
<style lang="scss" scoped>
.title {
  display: flex;
  justify-content: space-between;

  .download {
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }
}
</style>
